<template>
    <el-form label-width="80px" v-if="isLogin">
        <el-form-item label="标题">
            <el-input v-model="title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容">
            <div style="border: 1px solid #ccc;">
                <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                    mode="default" />
                <Editor style="height: 300px;overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
                    mode="default" @onCreated="handleCreated" />
            </div>

            <!-- <el-input v-model="form.content" type="textarea" placeholder="请输入内容" /> -->
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="addArticle">提交</el-button>
        </el-form-item>
    </el-form>

    <hr>

    <el-table :data="articles" style="width: 100%">
        <!-- <el-table-column prop="title" label="标题" width="400" /> -->

        <el-table-column label="标题" width="300">
            <template #default="scope">
                <!-- <el-link :href="'articledetail?id='+scope.row.id" target="_blank"                   >
                    {{ scope.row.title }}
                </el-link> -->

             <router-link :to="{name:'ArticleDetail',query:{id:scope.row.id} }">   {{ scope.row.title }}</router-link>   <span style="margin-left: 10px"></span>
        
            </template>
        </el-table-column>
        <el-table-column prop="authorName" label="作者" width="180" />
        <el-table-column prop="addedTime" label="时间" width="180" />
    </el-table>
</template>

<script setup lang="ts">
//帮我生成一个表单，里面包含标题，内容和提交按钮
import { ref, reactive, onMounted, onBeforeUnmount, shallowRef } from 'vue'
import '@wangeditor/editor/dist/css/style.css'
// 添加 wangeditor 的类型声明
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getList, add } from '../utils/request'
import { useUserStore } from '../stores/user';
import { ElMessageBox } from 'element-plus';

const userStore = useUserStore();
const isLogin = ref(userStore.isAuthenticated)
const editorRef = shallowRef()
// 工具栏配置
const toolbarConfig = reactive({
    // toolbarKeys: ['headerSelect', 'bold', itemMenu.value]
    excludeKeys: ['blockquote', 'headerSelect', 'color', 'bgColor', 'fontSize', 'fontFamily',
        'lineHeight', '|', 'group-more-style', 'group-indent', 'emotion', 'bulletedList', 'numberedList', 'divider', 'todo'],
    // insertKeys: {
    //   keys: itemMenu.value
    // }
})

const form = reactive({
    title: '',
    content: '',
})

const title = ref('')
const user = ref(userStore.getUser)
const addArticle = async () => {
    if (user.value && user.value.id) {
        const r = await add({
            title:title.value,
            body: valueHtml.value,
            userid: user.value.id
        })

        articles.value = await getList()
    }else{
        ElMessageBox.alert('请先登录', '提示').then(() => {
            // on confirm
        }).catch(() => {
            // on cancel
        });
    }

}
// 内容 HTML
const valueHtml = ref('')


const editorConfig = { 
    placeholder: '请输入内容...' ,
    MENU_CONF: {       
        uploadImage: {
            server: '/api/demo/image', // 上传图片的接口地址,
            maxFileSize: 10 * 1024 * 1024, // 10M
            onFailed(file, res) {
                console.log(`${file.name} 上传图片失败`, res)
            },
            // 上传错误，或者触发 timeout 超时
            onError(file, err, res) {
                const showSize = getShortSizeStr(this.maxFileSize)
                ElMessageBox.alert('上传图片失败,最大不能超过' + showSize)
                console.log(`${file.name} 上传图片出错`, err, res)
            },
        },
        uploadVideo: {
            server: '/api/demo/video',
            maxFileSize: 50 * 1024 * 1024, // 50M
            onFailed(file, res) {
                console.log(`${file.name} 上传视频失败`, res)

            },
            // 上传错误，或者触发 timeout 超时
            onError(file, err, res) {
                const showSize = getShortSizeStr(this.maxFileSize)
                ElMessageBox.alert('上传视频失败,最大不能超过' + showSize)
                console.log(`${file.name} 上传视频出错`, err, res)
            },
        }
    }

}
function getShortSizeStr(realSize: number, fixedLength = 0) {

    let showSize = ''
    if (realSize < 1024 * 1024) {
        showSize = (realSize / 1024).toFixed(fixedLength) + 'KB'
    } else {
        showSize = (realSize / (1024 * 1024)).toFixed(fixedLength) + 'MB'
    }

    return showSize

}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor: IDomEditor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

const articles = ref<Article[]>([])

onMounted(async () => {
    try {
        const data = await getList(1)
        articles.value = data  //可放到会话缓存
    } catch (error) {
        console.error('获取文章列表失败:', error)
    }
})
</script>

<style scoped></style>